package com.szpt.mo.bhubackground.controller.user;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.szpt.mo.bhubackground.controller.image.VerifyCodeController;
import com.szpt.mo.bhubackground.entity.TbUser;
import com.szpt.mo.bhubackground.entity.parameters.P_Login;
import com.szpt.mo.bhubackground.entity.parameters.P_UserUpdate;
import com.szpt.mo.bhubackground.service.ITbUserService;
import com.szpt.mo.bhubackground.util.config.Db;
import com.szpt.mo.bhubackground.util.config.JWTUtils;
import com.szpt.mo.bhubackground.util.config.StatusCheckUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import com.szpt.mo.bhubackground.entity.parameters.R_Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @Package: com.szpt.mo.bhubackground.entity.TbUser
 * @Description: <前端控制器>
 * @Author: mo
 * @CreateDate: 2022-06-05
 * @UpdateUser: mo
 * @UpdateDate: 2022-06-05
 * @UpdateRemark: <>
 * @Version: 1.0
 */
@RestController
@Api(tags = "TbUser-相关接口")
@RequestMapping(value = "/user")
public class TbUserController {

    private static final Logger logger = LoggerFactory.getLogger(TbUserController.class);

    @Autowired
    private ITbUserService service;

//    @Autowired
//    private Db db;


    @ApiOperation(value = "用户登出")
    @GetMapping("/logout")
    public boolean logout(HttpServletRequest request) {
        request.getSession().setMaxInactiveInterval(-1);
        return true;
    }


    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public R_Result<TbUser> login(@Validated @RequestBody P_Login pLogin, HttpServletRequest request) {


        HttpSession session = request.getSession();
        String verifyCode = (String) session.getAttribute(VerifyCodeController.LOGIN_VERIFY_CODE);
        if (verifyCode == null) {
            return new R_Result<TbUser>(null, "已过期请刷新二维码！", 500);
        }

        if (!pLogin.getCode().equals(verifyCode)) {
            return new R_Result<TbUser>(null, "二维码不正确", 500);
        }


        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("mail", pLogin.getAccount());
        wrapper.eq("password", pLogin.getPassword());

        TbUser one = service.getOne(wrapper);
//        TbUser one = service.login1(pLogin.getAccount(), pLogin.getPassword());
        if (one != null) {
            HttpSession session1 = request.getSession(true);
            session1.setMaxInactiveInterval(60 * 60 * 2);
            session1.setAttribute("user", one);
            one.setPassword("");

            return new R_Result<TbUser>(one, "登录成功", 200);
        }

        return new R_Result<TbUser>(null, "登录失败", 500);
    }


    @GetMapping("/getUser")
    public R_Result<TbUser> getUser(HttpServletRequest request) {
        TbUser login = StatusCheckUtils.isLogin(request);
        if (null == login) {
            return new R_Result<TbUser>(null, "请登录", 500);
        }
        return new R_Result<TbUser>(login, "登录成功", 200);
    }


/*
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public R_Result<String> login(@Validated @RequestBody P_Login pLogin, HttpServletRequest request) {

//        if ("mo@qq.com".equals(pLogin.getUsername())) {
//            if ("123456".equals(pLogin.getPassword())) {
//                new R_Result<Boolean>(true, "success", 200);
//            }
//        }

        String verifyCode = (String) request.getSession().getAttribute(VerifyCodeController.LOGIN_VERIFY_CODE);
        if (verifyCode == null) {
            return new R_Result<String>("", "不存在 请刷新二维码！", 200);
        }

        if (!pLogin.getCode().equals(verifyCode)) {
            return new R_Result<String>("", "二维码不正确" + pLogin.getCode() + "  " + verifyCode, 200);
        }

        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("mail", pLogin.getAccount());
        wrapper.eq("password", pLogin.getPassword());

        TbUser one = service.getOne(wrapper);
        if (one != null) {
            HashMap<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(one.getId()));
            payload.put("role", "admin");
            String token = JWTUtils.getToken(payload);
            return new R_Result<String>(token, "登录成功", 200);
        }

        return new R_Result<String>("", "fail", 404);
    }
*/


    @GetMapping("{id}")
    @ApiOperation(value = "获取某一实体")
    @ResponseBody

    public R_Result<TbUser> getITbUserServiceDetails(@PathVariable Long id) {
        TbUser byId = service.getById(id);
        byId.setPhone("");

        return new R_Result<TbUser>(byId, "success", 200);
    }

    @PostMapping("/register")
    @ApiOperation(value = "新增数据")
    @ResponseBody
    public R_Result<Boolean> saveITbUserService(@RequestBody @Validated TbUser dto) {
        boolean save = service.save(dto);
        R_Result<Boolean> result = new R_Result<>(save, "用户注册成功", 200);
        return result;
    }

    @PutMapping("{id}")
    @ApiOperation(value = "修改数据")
    @ResponseBody
    public R_Result<Boolean> modifyITbUserService(@RequestBody P_UserUpdate dto, @PathVariable Long id, HttpServletRequest request) {

        TbUser login = StatusCheckUtils.isLogin(request);

        if (!StatusCheckUtils.isAdmin(request) || (long) login.getId() != (long) id) {
            return new R_Result<Boolean>(false, "非法修改", 600);
        }

        UpdateWrapper<TbUser> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        boolean success = false;
        wrapper.set("phone", dto.getPhone());

        if (!StringUtils.isEmpty(dto.getPassword())) {
            int length = dto.getPassword().length();
            if (length < 2 || length > 32) {
                return new R_Result<Boolean>(false, "密码格式错误", 600);
            }
            wrapper.set("password", dto.getPhone());
        }

        wrapper.set("name", dto.getName());
        wrapper.set("avatar", dto.getAvatar());

        success = service.update(wrapper);

        return new R_Result<>(success, success ? "成功" : "失败", success ? 200 : 500);
    }

//    @DeleteMapping("batch")
//    @ApiOperation(value = "批量删除数据")
//    @ResponseBody
//    public boolean batchRemoveITbUserService(@RequestParam(value = "ids") List<Long> ids) {
//        return service.removeByIds(ids);
//    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "删除数据")
    @ResponseBody
    public R_Result<Boolean> removeITbUserService(@PathVariable Long id) {
        boolean success = false;
        success = service.removeById(id);
        return new R_Result<Boolean>(success, success ? "成功" : "失败", success ? 200 : 500);
    }

    @GetMapping("/getList/{current}/{size}/{total}")
    @ApiOperation(value = "TT 获取列表数据")
    @ResponseBody
    public R_Result<List<TbUser>> addTbUser(HttpServletRequest request, @PathVariable Integer current, @PathVariable Integer size, @PathVariable Integer total) {


        if (!StatusCheckUtils.isAdmin(request)) {
            return new R_Result<List<TbUser>>(null, "非法请求", 500);
        }

        boolean save = false;
        R_Result<List<TbUser>> result = new R_Result<>();

        try {
            //String id = JWTUtils.getTokenPayload(request).getId();

            //添加查询条件
            QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
            Page<TbUser> page = new Page<>(current, size, total);
            result.setData(service.page(page, wrapper).getRecords());


            save = true;

        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }

        if (save) {
            result.setCode(200);
            result.setMsg("成功");
        } else {
            result.setCode(250);
            result.setMsg("失败");
        }
        return result;
    }

    @GetMapping("/getList/{search}/{current}/{size}/{total}")
    @ApiOperation(value = "TT 获取列表数据")
    @ResponseBody
    public R_Result<List<TbUser>> addTbUser(HttpServletRequest request, @PathVariable String search, @PathVariable Integer current, @PathVariable Integer size, @PathVariable Integer total) {

        if (!StatusCheckUtils.isAdmin(request)) {
            return new R_Result<List<TbUser>>(null, "非法请求", 500);
        }


        boolean save = false;
        R_Result<List<TbUser>> result = new R_Result<>();

        try {
            //String id = JWTUtils.getTokenPayload(request).getId();

            //添加查询条件
            QueryWrapper<TbUser> wrapper = new QueryWrapper<>();

//            wrapper.like("name", search);
//            wrapper.like("mail", search);
//            wrapper.like("phone", search);

            Page<TbUser> page = new Page<>(current, size, total);

            result.setData(service.page(page, wrapper).getRecords());
            save = true;

        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }

        if (save) {
            result.setCode(200);
            result.setMsg("成功");
        } else {
            result.setCode(250);
            result.setMsg("失败");
        }
        return result;
    }


//    @GetMapping("/edit")
//    @ApiOperation(value = "TT 编辑数据")
//    @ResponseBody
//    public R_Result<Boolean> editTbUser(HttpServletRequest request, @RequestBody TbUser otd) {
//
//        boolean save = false;
//        R_Result<Boolean> result = new R_Result<>();
//        try {
//
////            String userid = JWTUtils.getTokenPayload(request).getId();
//
//            UpdateWrapper<TbUser> wrapper = new UpdateWrapper<>();
//
////            wrapper.eq("user_id", userid);
//            wrapper.eq("id", otd.getId());
//            //设置更新value
////            wrapper.set("name", name);
//
//
//            save = service.update(otd, wrapper);
//
//        } catch (Exception e) {
//            result.setMsg(e.getMessage());
//            e.printStackTrace();
//        }
//
//        if (save) {
//            result.setCode(200);
//            result.setMsg("成功");
//        } else {
//            result.setCode(250);
//            result.setMsg("失败");
//        }
//        result.setData(save);
//        return result;
//    }


}
